<?php

/**
 * 核销码生成功能测试
 * 使用方法：php test_ticket_generation.php
 */

require_once __DIR__ . '/vendor/autoload.php';

use app\model\BizGoodsTicketModel;
use app\model\BizGoodsOrderModel;

// 模拟订单数据
$mockOrder = new BizGoodsOrderModel();
$mockOrder->id = 1;
$mockOrder->biz_goods_id = 1;
$mockOrder->biz_id = 1;
$mockOrder->quantity = 3; // 生成3个核销码

echo "开始测试核销码生成功能...\n";

try {
    // 测试生成核销码
    echo "1. 测试生成核销码...\n";
    $tickets = BizGoodsTicketModel::generateTickets($mockOrder);
    
    echo "生成成功！生成了 " . count($tickets) . " 个核销码：\n";
    foreach ($tickets as $index => $ticket) {
        echo "  核销码 " . ($index + 1) . ": " . $ticket->code . "\n";
    }
    
    // 测试批量保存
    echo "\n2. 测试批量保存...\n";
    $result = BizGoodsTicketModel::batchSaveTickets($tickets);
    
    if ($result) {
        echo "批量保存成功！\n";
    } else {
        echo "批量保存失败！\n";
    }
    
    // 测试唯一性检查
    echo "\n3. 测试核销码唯一性...\n";
    $existingCodes = [];
    foreach ($tickets as $ticket) {
        if (in_array($ticket->code, $existingCodes)) {
            echo "错误：发现重复的核销码: " . $ticket->code . "\n";
        } else {
            $existingCodes[] = $ticket->code;
        }
    }
    
    if (count($existingCodes) === count($tickets)) {
        echo "核销码唯一性检查通过！\n";
    }
    
    // 测试性能
    echo "\n4. 测试性能（生成100个核销码）...\n";
    $startTime = microtime(true);
    
    $mockOrderLarge = new BizGoodsOrderModel();
    $mockOrderLarge->id = 2;
    $mockOrderLarge->biz_goods_id = 1;
    $mockOrderLarge->biz_id = 1;
    $mockOrderLarge->quantity = 100;
    
    $ticketsLarge = BizGoodsTicketModel::generateTickets($mockOrderLarge);
    
    $endTime = microtime(true);
    $executionTime = $endTime - $startTime;
    
    echo "生成100个核销码耗时: " . round($executionTime, 4) . " 秒\n";
    echo "平均每个核销码生成时间: " . round($executionTime / 100, 6) . " 秒\n";
    
    echo "\n测试完成！\n";
    
} catch (Exception $e) {
    echo "测试失败: " . $e->getMessage() . "\n";
} 